#include <Shader.hpp>
#include <fstream>
#include <string>

using namespace std;

namespace Olorin
{
	namespace Graphics
	{
		Shader::Shader()
		{
			shaderType = VertexShader;
			original = true;
			shaderID = glCreateShader(shaderType);
		}
		
		Shader::Shader(const ShaderType& shaderType, const char* filename)
		{
			this->shaderType = shaderType;
			original = true;
			shaderID = glCreateShader(shaderType);
			if(load(filename))
				compile();
		}
		
		Shader::Shader(const Shader& source)
		{
			shaderType = source.shaderType;
			shaderID = source.shaderID;
			original = false;
		}
		
		Shader::~Shader()
		{
			if(original)
				glDeleteShader(shaderID);
		}
		
		
		// accessor functions
		const ShaderType& Shader::getShaderType() const
		{
			return shaderType;
		}
		
		const GLuint& Shader::getShaderID() const
		{
			return shaderID;
		}
		
		
		const bool Shader::load(const char* filename)
		{
			ifstream infile(filename);
			if(!infile)
				return false;
			string text;
			char buffer[256];
			while(!infile.eof())
			{
				infile.getline(buffer, 256);
				text = text + string(buffer) + string("\n");
			}
			infile.close();
			const char* shaderText = text.c_str();
			glShaderSource(shaderID, 1, &shaderText, NULL);
			return true;
		}
		
		const bool Shader::compile()
		{
			int errCode = false;
			glCompileShader(shaderID);
			glGetShaderiv(shaderID, GL_COMPILE_STATUS, &errCode);
			return errCode != 0;
		}
	}
}
